Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Install Datasets and Upgrade TensorFlow

To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.

  • tensorflow-datasets is the stable version that is released on a cadence of every few months
  • tfds-nightly is released every day and has the latest version of the datasets

We'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.

In [1]:
%pip --no-cache-dir install tensorflow-datasets --user --quiet
%pip --no-cache-dir install tfds-nightly --user --quiet
%pip --no-cache-dir install --upgrade tensorflow --user --quiet
Note: you may need to restart the kernel to use updated packages.
Note: you may need to restart the kernel to use updated packages.
Note: you may need to restart the kernel to use updated packages.

After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.

In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub

# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')

import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
In [2]:
# TODO: Make all other necessary imports.
import numpy as np
import matplotlib.pyplot as plt
import os
import json
import time
from PIL import Image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
In [3]:
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()
os.environ['AUTOGRAPH_VERBOSITY'] = '0'
In [4]:
# Define helper functions
def plot_image(image, label):
    fig, (ax1) = plt.subplots(figsize=(6,9), ncols=1)
    ax1.imshow(image, cmap = plt.cm.binary)
    ax1.axis('off')
    ax1.set_title('Label: {}'.format(str(label)))
    plt.show()

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [5]:
# Importing the dataset using the official splits

DATASET_NAME = 'oxford_flowers102'

# Using test split as train dataset and train split as test dataset
# as per discussion here: https://github.com/tensorflow/datasets/issues/3022
# It gives better accuracy (88.039% instead of around 78%), and significantly
# improves results for orange_dahlia.jpg, making correct prediction with 
# probability close to 0.9
(test_set, train_set, validation_set), dataset_info = tfds.load(DATASET_NAME, split=['train', 'test', 'validation'], as_supervised=True, with_info=True)

Explore the Dataset

In [6]:
# TODO: Get the number of examples in each set from the dataset info.
train_num_examples = len(train_set)
test_num_examples = len(test_set)
validation_num_examples = len(validation_set)

# TODO: Get the number of classes in the dataset from the dataset info.
num_classes = dataset_info.features['label'].num_classes

print('This Dataset includes:')
print('\u2022 {:,} train images'.format(train_num_examples))
print('\u2022 {:,} test images'.format(test_num_examples))
print('\u2022 {:,} validation images'.format(validation_num_examples))
print('\u2022 {:,} classes'.format(num_classes))
This Dataset includes:
• 6,149 train images
• 1,020 test images
• 1,020 validation images
• 102 classes
In [7]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in train_set.take(3):
    print('The image shape is {} and the corresponding label is {}'.format(image.shape, label))
The image shape is (542, 500, 3) and the corresponding label is 40
The image shape is (748, 500, 3) and the corresponding label is 76
The image shape is (500, 600, 3) and the corresponding label is 42
In [8]:
# TODO: Plot 1 image from the training set.
# Set the title of the plot to the corresponding image label.
for image, label in train_set.take(1):
    plot_image(image.numpy(), label.numpy())

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [9]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
    
def get_class_name_by_label(label):
    return class_names[str(label + 1)].title()
In [10]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name.
for image, label in train_set.take(1):
    plot_image(image.numpy(), get_class_name_by_label(label.numpy()))

Create Pipeline

In [11]:
# TODO: Create a pipeline for each set.
BATCH_SIZE = 16
IMAGE_SIZE = 224
CROP_IMAGE_SIZE = int(IMAGE_SIZE * 1.45)

# Experimental, gives a bit worse results
def transform_image_with_crop(image):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize_with_pad(image, CROP_IMAGE_SIZE, CROP_IMAGE_SIZE)
    image = tf.image.central_crop(image, .65)
    image = tf.image.resize(image, (IMAGE_SIZE, IMAGE_SIZE), preserve_aspect_ratio=True)
    image /= 255
    
    return image

def transform_image(image):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
    image /= 255
    
    return image

@tf.autograph.experimental.do_not_convert
def format_image(image, label):
    return transform_image(image), label

training_batches = train_set.shuffle(train_num_examples//4).map(format_image).batch(BATCH_SIZE).prefetch(1)
validation_batches = validation_set.map(format_image).batch(BATCH_SIZE).prefetch(1)
testing_batches = test_set.map(format_image).batch(BATCH_SIZE).prefetch(1)
In [12]:
# Plot images from train batch
for image_batch, label_batch in training_batches.take(1):
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()

    # Plot the image
for image_index in range(BATCH_SIZE):
    plt.imshow(images[image_index], cmap = plt.cm.binary)
    plt.colorbar()
    plt.show()

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [13]:
# TODO: Build and train your network.
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"

feature_extractor = hub.KerasLayer(URL, input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3))
feature_extractor.trainable = False

model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dropout(0.2),
        tf.keras.layers.Dense(num_classes, activation = 'softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.summary()
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f88bc813050>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dropout (Dropout)           (None, 1280)              0         
                                                                 
 dense (Dense)               (None, 102)               130662    
                                                                 
=================================================================
Total params: 2,388,646
Trainable params: 130,662
Non-trainable params: 2,257,984
_________________________________________________________________
In [14]:
# Train the model
EPOCHS = 20
timestamp = int(time.time())
best_model_filename = '{}_{}_best_model.h5'.format(DATASET_NAME, timestamp)

early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_accuracy', patience=2)

save_best = tf.keras.callbacks.ModelCheckpoint(best_model_filename,
                                               monitor='val_accuracy',
                                               save_best_only=True)

history = model.fit(training_batches,
                    epochs=EPOCHS,
                    validation_data=validation_batches,
                    callbacks=[early_stopping, save_best])
Epoch 1/20
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7f88bc3fbd40> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
385/385 [==============================] - ETA: 0s - loss: 1.7520 - accuracy: 0.6188WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7f88bc319830> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
385/385 [==============================] - 135s 336ms/step - loss: 1.7520 - accuracy: 0.6188 - val_loss: 0.8204 - val_accuracy: 0.8098
Epoch 2/20
385/385 [==============================] - 130s 333ms/step - loss: 0.4804 - accuracy: 0.8984 - val_loss: 0.5691 - val_accuracy: 0.8706
Epoch 3/20
385/385 [==============================] - 131s 336ms/step - loss: 0.2851 - accuracy: 0.9393 - val_loss: 0.4752 - val_accuracy: 0.8853
Epoch 4/20
385/385 [==============================] - 131s 336ms/step - loss: 0.1936 - accuracy: 0.9632 - val_loss: 0.4310 - val_accuracy: 0.8941
Epoch 5/20
385/385 [==============================] - 130s 334ms/step - loss: 0.1347 - accuracy: 0.9798 - val_loss: 0.4101 - val_accuracy: 0.8961
Epoch 6/20
385/385 [==============================] - 129s 332ms/step - loss: 0.1070 - accuracy: 0.9828 - val_loss: 0.4087 - val_accuracy: 0.8951
Epoch 7/20
385/385 [==============================] - 129s 330ms/step - loss: 0.0811 - accuracy: 0.9894 - val_loss: 0.3839 - val_accuracy: 0.9000
Epoch 8/20
385/385 [==============================] - 125s 321ms/step - loss: 0.0636 - accuracy: 0.9924 - val_loss: 0.3723 - val_accuracy: 0.9029
Epoch 9/20
385/385 [==============================] - 128s 330ms/step - loss: 0.0529 - accuracy: 0.9938 - val_loss: 0.3660 - val_accuracy: 0.9039
Epoch 10/20
385/385 [==============================] - 129s 331ms/step - loss: 0.0452 - accuracy: 0.9948 - val_loss: 0.3767 - val_accuracy: 0.9000
Epoch 11/20
385/385 [==============================] - 124s 318ms/step - loss: 0.0380 - accuracy: 0.9959 - val_loss: 0.3889 - val_accuracy: 0.8990
In [15]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(len(training_loss))

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [16]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
64/64 [==============================] - 18s 284ms/step - loss: 0.4184 - accuracy: 0.8804

Loss on the TEST Set: 0.418
Accuracy on the TEST Set: 88.039%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [17]:
# TODO: Save your trained model as a Keras model.
timestamp = int(time.time())
model_filename = '{}_{}_model.h5'.format(DATASET_NAME, timestamp)

model.save(model_filename)

Load the Keras Model

Load the Keras model you saved above.

In [19]:
# TODO: Load the Keras model
reloaded_model = tf.keras.models.load_model(model_filename, custom_objects = { 'KerasLayer': feature_extractor })

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [20]:
# TODO: Create the process_image function
def process_image(image):   
    return transform_image(image)

def load_image(image_path):
    image = Image.open(image_path)

    return np.asarray(image)

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [21]:
from PIL import Image

image_path = './test_images/hard-leaved_pocket_orchid.jpg'
image = load_image(image_path)

processed_test_image = process_image(image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [22]:
# TODO: Create the predict function
def predict(image_path, model, top_k):
    image = load_image(image_path)
    processed_test_image = np.expand_dims(process_image(image), axis=0)
    predictions = model.predict(processed_test_image)[0]
    
    ind = np.argpartition(predictions, -top_k)[-top_k:]
    
    return image, predictions[ind], map(lambda index: get_class_name_by_label(index), ind)

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [24]:
# TODO: Plot the input image along with the top 5 classes
images = ['cautleya_spicata', 'hard-leaved_pocket_orchid', 'orange_dahlia', 'wild_pansy']
images = map(lambda name: [
    predict('./test_images/{}.jpg'.format(name), reloaded_model, 5), 
    name.replace('_', ' ').title(),
], images)

for (image, probs, classes), label in images:
    fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
    ax1.imshow(image, cmap = plt.cm.binary)
    ax1.axis('off')
    ax1.set_title(label)
    ax2.barh(np.arange(5), probs)
    ax2.set_aspect(0.1)
    ax2.set_yticks(np.arange(5))
    ax2.set_yticklabels(classes, size='small');
    ax2.set_title('Class Probability')
    ax2.set_xlim(0, 1.1)
    plt.tight_layout()
1/1 [==============================] - 0s 42ms/step
1/1 [==============================] - 0s 51ms/step
1/1 [==============================] - 0s 51ms/step
1/1 [==============================] - 0s 54ms/step
In [26]:
# Using test split as train dataset and train split as test dataset
# gives better accuracy (88.039% instead of around 78%), and significantly
# improves results for orange_dahlia.jpg, making correct prediction with 
# probability close to 0.9
In [ ]: